<template>
  <div class="pattern-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>匹配规则管理</h2>
          <div class="header-actions">
            <!-- 添加批量操作按钮 -->
            <el-button
                type="danger"
                :disabled="!store.selectedPatterns.length"
                @click="handleBatchDelete"
            >
              批量删除
            </el-button>
            <el-button
                type="primary"
                :disabled="!store.selectedPatterns.length"
                @click="handleBatchToggle(true)"
            >
              批量启用
            </el-button>
            <el-button
                type="warning"
                :disabled="!store.selectedPatterns.length"
                @click="handleBatchToggle(false)"
            >
              批量禁用
            </el-button>
            <el-button type="warning" @click="handleRefreshCache">
              刷新缓存
            </el-button>
            <el-button type="primary" @click="showAddDialog">
              新增规则
            </el-button>
          </div>
        </div>
      </template>

      <!-- 过滤器 -->
      <div class="filter-section">
        <el-select
            v-model="selectedFieldType"
            placeholder="选择字段类型"
            clearable
            @change="handleFilterChange"
        >
          <el-option
              v-for="type in fieldTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
          />
        </el-select>
      </div>

      <!-- 规则列表 -->
      <el-table
          v-loading="store.loading"
          :data="store.patterns"
          border
          @selection-change="handleSelectionChange"
          style="width: 100%"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column prop="fieldType" label="字段类型">
          <template #default="scope">
            {{ getFieldTypeLabel(scope.row.fieldType) }}
          </template>
        </el-table-column>
        <el-table-column prop="pattern" label="匹配规则" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-switch
                v-model="scope.row.isEnabled"
                @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button
                type="primary"
                link
                @click="showEditDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
                type="danger"
                link
                @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            :current-page="store.pagination.current"
            :page-size="store.pagination.size"
            :total="store.pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑对话框 -->
      <el-dialog
          v-model="dialogVisible"
          :title="editingPattern.id ? '编辑规则' : '新增规则'"
          width="500px"
      >
        <el-form
            ref="patternForm"
            :model="editingPattern"
            :rules="rules"
            label-width="100px"
        >
          <el-form-item label="字段类型" prop="fieldType">
            <el-select v-model="editingPattern.fieldType" placeholder="请选择字段类型">
              <el-option
                  v-for="type in fieldTypes"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="匹配规则" prop="pattern">
            <el-input v-model="editingPattern.pattern" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="editingPattern.description" type="textarea" />
          </el-form-item>
          <el-form-item label="状态">
            <el-switch v-model="editingPattern.isEnabled" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave" :loading="saving">
              保存
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { usePatternStore } from '@/stores/adminPattern'
import { format } from 'date-fns'

const store = usePatternStore()
const dialogVisible = ref(false)
const saving = ref(false)
const selectedFieldType = ref(null)
const patternForm = ref(null)

// 处理选择变化
const handleSelectionChange = (selection) => {
  store.setSelectedPatterns(selection)
}

// 字段类型选项
const fieldTypes = [
  { label: '评论内容', value: 'COMMENT' },
  { label: '作者名称', value: 'AUTHOR' },
  { label: '邮箱', value: 'EMAIL' },
  { label: '网站链接', value: 'URL' }
]

const editingPattern = reactive({
  id: null,
  fieldType: '',
  pattern: '',
  description: '',
  isEnabled: true
})

const rules = {
  fieldType: [{ required: true, message: '请选择字段类型', trigger: 'change' }],
  pattern: [{ required: true, message: '请输入匹配规则', trigger: 'blur' }]
}

// 批量删除
const handleBatchDelete = async () => {
  if (!store.selectedPatterns.length) {
    ElMessage.warning('请选择要删除的规则')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的${store.selectedPatterns.length}个规则吗？`
    )
    const ids = store.selectedPatterns.map(item => item.id)
    const success = await store.batchDeletePatterns(ids)
    if (success) {
      ElMessage.success('批量删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量启用/禁用
const handleBatchToggle = async (enabled) => {
  if (!store.selectedPatterns.length) {
    ElMessage.warning('请选择要操作的规则')
    return
  }

  try {
    const action = enabled ? '启用' : '禁用'
    await ElMessageBox.confirm(
        `确定要${action}选中的${store.selectedPatterns.length}个规则吗？`
    )
    const ids = store.selectedPatterns.map(item => item.id)
    const success = await store.batchUpdateStatus(ids, enabled)
    if (success) {
      ElMessage.success(`批量${action}成功`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`批量${enabled ? '启用' : '禁用'}失败`)
    }
  }
}

// 刷新缓存
const handleRefreshCache = async () => {
  try {
    await store.refreshPatternCache()
    ElMessage.success('缓存刷新成功')
  } catch (error) {
    ElMessage.error('缓存刷新失败')
  }
}

// 显示新增对话框
const showAddDialog = () => {
  Object.assign(editingPattern, {
    id: null,
    fieldType: '',
    pattern: '',
    description: '',
    isEnabled: true
  })
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (pattern) => {
  Object.assign(editingPattern, pattern)
  dialogVisible.value = true
}

// 保存规则
const handleSave = async () => {
  if (!patternForm.value) return

  await patternForm.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        if (editingPattern.id) {
          await store.updatePattern(editingPattern.id, editingPattern)
        } else {
          await store.addPattern(editingPattern)
        }
        ElMessage.success('保存成功')
        dialogVisible.value = false
        await store.fetchPatterns()
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }
  })
}

// 删除规则
const handleDelete = async (pattern) => {
  try {
    await ElMessageBox.confirm('确定要删除此规则吗？')
    await store.deletePattern(pattern.id)
    ElMessage.success('删除成功')
    await store.fetchPatterns()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 状态改变处理
const handleStatusChange = async (pattern) => {
  try {
    await store.updatePattern(pattern.id, pattern)
    ElMessage.success('状态更新成功')
  } catch (error) {
    pattern.isEnabled = !pattern.isEnabled
    ElMessage.error('状态更新失败')
  }
}

// 过滤器改变
const handleFilterChange = (value) => {
  store.setFilter(value)
}

// 分页处理
const handleSizeChange = (size) => {
  store.fetchPatterns({ size })
}

const handleCurrentChange = (current) => {
  store.fetchPatterns({ current })
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '--'
  return format(new Date(time), 'yyyy-MM-dd HH:mm:ss')
}

// 获取字段类型标签
const getFieldTypeLabel = (type) => {
  const fieldType = fieldTypes.find(t => t.value === type)
  return fieldType ? fieldType.label : type
}

onMounted(() => {
  store.fetchPatterns()
})
</script>